package com.vids.hikcam;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sun.jna.Pointer;
import com.vids.hikcam.common.osSelect;
import com.vids.hikcam.common.HCNetSDK;
import com.sun.jna.Native;
import com.vids.mapper.ApeMapper;
import com.vids.model.entity.Ape;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Scanner;

@Slf4j

public class HIKCamAlarm {

//    @Lazy
//    @Autowired
//    @Resource
//    private static ApeMapper apeMapper;

    //声明要注入的Bean变量
    private static ApeMapper apeMapper;
    // 通过applicationContext上下文获取Bean

    public static void setApplicationContext(ApplicationContext applicationContext) {
        apeMapper = applicationContext.getBean(ApeMapper.class);
    }



    static HCNetSDK hCNetSDK = null;

    static boolean SdkInited = false;
    static int lUserID = -1;//用户句柄

    static int lAlarmHandle =-1;//报警布防句柄

    static String m_sDeviceIP;//已登录设备的IP地址

    static FMSGCallBack_V31 fMSFCallBack_V31 = null;

    static FMSGCallBack_V31 fMSFCallBack=null;

    static final Object alarmLock = new Object();
    /**
     * 根据不同操作系统选择不同的库文件和库路径
     *
     * @return
     */
    private static boolean createSDKInstance() {
        if (hCNetSDK == null) {
            synchronized (HCNetSDK.class) {
                String strDllPath = "";
                try {
                    System.setProperty("jna.debug_load", "true");
                    //if (osSelect.isLinux())
                    if (osSelect.isWindows())
                        //win系统加载库路径
                        strDllPath = System.getProperty("user.dir") + "\\src\\main\\resources\\lib\\HCNetSDK.dll";
                    else
                        //Linux系统加载库路径 System.getProperty("user.dir") +
                        strDllPath = "/usr/lib64/libhcnetsdk.so";
                    System.setProperty("jna.library.path", "/usr/lib64");

                    log.info("libhcnetsdk strDllPath=====>" + strDllPath);
                    hCNetSDK = (HCNetSDK)Native.loadLibrary(strDllPath, HCNetSDK.class);
                } catch (Exception ex) {
                    log.info("LoadLibrary: " + strDllPath + " Error: " + ex.getMessage());
                    return false;
                }
            }
        }
        return true;
    }


    /**
     * 设备登录V40 与V30功能一致
     * @param ip   设备IP
     * @param port SDK端口，默认设备的8000端口
     * @param user 设备用户名
     * @param psw  设备密码
     */
    public static int login_V40(String ip, short port, String user, String psw) {
        //注册
        HCNetSDK.NET_DVR_USER_LOGIN_INFO m_strLoginInfo = new HCNetSDK.NET_DVR_USER_LOGIN_INFO();//设备登录信息
        HCNetSDK.NET_DVR_DEVICEINFO_V40 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V40();//设备信息

        String m_sDeviceIP = ip;//设备ip地址
        m_strLoginInfo.sDeviceAddress = new byte[HCNetSDK.NET_DVR_DEV_ADDRESS_MAX_LEN];
        System.arraycopy(m_sDeviceIP.getBytes(), 0, m_strLoginInfo.sDeviceAddress, 0, m_sDeviceIP.length());

        String m_sUsername = user;//设备用户名
        m_strLoginInfo.sUserName = new byte[HCNetSDK.NET_DVR_LOGIN_USERNAME_MAX_LEN];
        System.arraycopy(m_sUsername.getBytes(), 0, m_strLoginInfo.sUserName, 0, m_sUsername.length());

        String m_sPassword = psw;//设备密码
        m_strLoginInfo.sPassword = new byte[HCNetSDK.NET_DVR_LOGIN_PASSWD_MAX_LEN];
        System.arraycopy(m_sPassword.getBytes(), 0, m_strLoginInfo.sPassword, 0, m_sPassword.length());

        m_strLoginInfo.wPort = port;
        m_strLoginInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是
        m_strLoginInfo.byLoginMode=0;  //ISAPI登录
        m_strLoginInfo.write();

        lUserID = hCNetSDK.NET_DVR_Login_V40(m_strLoginInfo, m_strDeviceInfo);
        if (lUserID== -1) {
            log.info("登录失败，错误码为" + hCNetSDK.NET_DVR_GetLastError());
        } else {
            log.info(ip + ":设备登录成功！");
        }
        return lUserID;
    }


    /**
     * 报警布防V50接口，功能和V41一致
     *
     * @param
     */
    public static boolean  setAlarm_V50(int userId) {

        int lAlarmHandle = -1 ;//尚未布防,需要布防

        //报警布防参数设置
        HCNetSDK.NET_DVR_SETUPALARM_PARAM_V50 m_strAlarmInfo = new HCNetSDK.NET_DVR_SETUPALARM_PARAM_V50();
        m_strAlarmInfo.dwSize = m_strAlarmInfo.size();
        m_strAlarmInfo.byLevel = 0;  //布防等级
        m_strAlarmInfo.byAlarmInfoType = 1;   // 智能交通报警信息上传类型：0- 老报警信息（NET_DVR_PLATE_RESULT），1- 新报警信息(NET_ITS_PLATE_RESULT)

        m_strAlarmInfo.byFaceAlarmDetection = 0;
        m_strAlarmInfo.byDeployType = 0;   //布防类型 0：客户端布防 1：实时布防
        m_strAlarmInfo.write();

        lAlarmHandle = hCNetSDK.NET_DVR_SetupAlarmChan_V50(userId, m_strAlarmInfo, Pointer.NULL, 0);

        log.info("lAlarmHandle: " + lAlarmHandle);

        if (lAlarmHandle == -1) {
            log.info("布防失败，错误码为" + hCNetSDK.NET_DVR_GetLastError());
            return false;
        } else {
            log.info("布防成功");
            return true;
        }
    }

    public static boolean setAlarm(int userId) {

        int lAlarmHandle = -1 ;//尚未布防,需要布防

        //报警布防参数设置
        HCNetSDK.NET_DVR_SETUPALARM_PARAM m_strAlarmInfo = new HCNetSDK.NET_DVR_SETUPALARM_PARAM();
        m_strAlarmInfo.dwSize = m_strAlarmInfo.size();
        m_strAlarmInfo.byLevel = 0;  //布防等级
        m_strAlarmInfo.byAlarmInfoType = 1;   // 智能交通报警信息上传类型：0- 老报警信息（NET_DVR_PLATE_RESULT），1- 新报警信息(NET_ITS_PLATE_RESULT)
        m_strAlarmInfo.byDeployType = 0;   //布防类型：0-客户端布防，1-实时布防
        m_strAlarmInfo.byFaceAlarmDetection = 0;
        m_strAlarmInfo.write();

        lAlarmHandle= hCNetSDK.NET_DVR_SetupAlarmChan_V41(userId, m_strAlarmInfo);
        log.info("lAlarmHandle: " + lAlarmHandle);
        if (lAlarmHandle == -1) {
            log.info("布防失败，错误码为" + hCNetSDK.NET_DVR_GetLastError());
            return false;
        } else {
            log.info("布防成功");
            return true;
        }

    }


//
//            switch (index) {
//                case 0: //软硬件能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_SOFTHARDWARE_ABILITY;
//                    break;
//                case 1: //Wifi能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_NETWORK_ABILITY;
//                    break;
//                case 2: //编码能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_ENCODE_ALL_ABILITY_V20;
//                    xmlInput = "<AudioVideoCompressInfo><AudioChannelNumber>1</AudioChannelNumber><VoiceTalkChannelNumber>1</VoiceTalkChannelNumber><VideoChannelNumber>1</VideoChannelNumber></AudioVideoCompressInfo>";
//                    break;
//                case 3: //设备前端参数能力
//                    m_dwAbilityType = hCNetSDK.IPC_FRONT_PARAMETER_V20;
//                    xmlInput = "<CAMERAPARA><ChannelNumber>1</ChannelNumber></CAMERAPARA>";
//                    break;
//                case 4: //Raid能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_RAID_ABILITY;
//                    break;
//                case 5: //设备报警能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_ALARM_ABILITY;
//                    xmlInput = "<AlarmAbility version='2.0'><channelID>1</channelID></AlarmAbility>";
//                    break;
//                case 6: //设备数字通道能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_DYNCHAN_ABILITY;
//                    xmlInput = "<DynChannelAbility version='2.0'><channelNO>1</channelNO></DynChannelAbility>";
//                    break;
//                case 7: //设备用户管理参数能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_USER_ABILITY;
//                    xmlInput = "<UserAbility version='2.0'/>";
//                    break;
//                case 8: //设备网络应用参数能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_NETAPP_ABILITY;
//                    xmlInput = "<NetAppAbility version='2.0'></NetAppAbility>";
//                    break;
//                case 9: //设备图像参数能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_VIDEOPIC_ABILITY;
//                    xmlInput = "<VideoPicAbility version='2.0'><channelNO>1</channelNO></VideoPicAbility>";
//                    break;
//                case 10: //设备JPEG抓图能力
//                    m_dwAbilityType = hCNetSDK.DEVICE_JPEG_CAP_ABILITY;
//                    xmlInput = "<JpegCaptureAbility version='2.0'><channelNO>1</channelNO></JpegCaptureAbility>";
//                    break;
//                case 11: //设备RS232和RS485串口能力
//                    m_dwAbilityType = hCNetSDK.VCA_DEV_ABILITY;
//                    xmlInput = "<SerialAbility version='2.0'/>";
//                    break;
//                case 12: //报警事件处理能力集
//                    m_dwAbilityType = hCNetSDK.DEVICE_ABILITY_INFO;
//                    xmlInput = "<EventAbility version='2.0'><channelNO>1</channelNO></EventAbility>";
//                    break;
//                default:
//                    m_dwAbilityType = 0;
//
//            }
//
//
//            HCNetSDK.BYTE_ARRAY ptrByteInput = new HCNetSDK.BYTE_ARRAY(256);
//            System.arraycopy(xmlInput.getBytes(), 0, ptrByteInput.byValue, 0, xmlInput.length());
//            ptrByteInput.write();

//            HCNetSDK.BYTE_ARRAY ptrByteOutput = new HCNetSDK.BYTE_ARRAY(XML_ABILITY_OUT_LEN);
//            ptrByteOutput.write();

    public static int getCameraDeviceAbility(int userId, String ip)
    {
        try {
//            int XML_ABILITY_OUT_LEN = 3 * 1024 * 1024;

            int XML_ABILITY_OUT_LEN = 64;
//            String xmlInput = "<EventAbility version='2.0'><channelNO>1</channelNO></EventAbility>";
//            int m_dwAbilityType = hCNetSDK.DEVICE_ABILITY_INFO;
//            String xmlInput = "<DevAbility version='2.0'><channelNO>1</channelNO></DevAbility>";
            int m_dwAbilityType = hCNetSDK.VCA_DEV_ABILITY;


            HCNetSDK.NET_VCA_DEV_ABILITY netVcaDevAbility = new HCNetSDK.NET_VCA_DEV_ABILITY();
            netVcaDevAbility.write();
//            Pointer pnetVcaDevAbility = netVcaDevAbility.getPointer();

//            hCNetSDK.NET_DVR_GetDeviceAbility(userId, m_dwAbilityType, ptrByteInput.getPointer(), xmlInput.length(),
//                    ptrByteOutput.getPointer(), XML_ABILITY_OUT_LEN);


            hCNetSDK.NET_DVR_GetDeviceAbility(userId, m_dwAbilityType, null, 0,
                                               netVcaDevAbility.getPointer(), netVcaDevAbility.size());

//            log.error("getCameraDeviceAbility ======>before read outputStr:\n" + ptrByteOutput.getPointer().getString(0));

            netVcaDevAbility.read();
//            String outputStr = ptrByteOutput.getPointer().getString(0);
            int size = netVcaDevAbility.getPointer().getInt(0);
//            遍历能力对象，获取能力字段和能力值
            Class<?> clazz = netVcaDevAbility.getClass();
            Field[] fields = clazz.getDeclaredFields();
            String ability = "";
            int index =0;
            for (Field field : fields) {
                try {
                    // 设置访问权限，因为有些字段可能是私有的
                    field.setAccessible(true);

                    // 获取字段名称
                    String fieldName = field.getName();

                    // 获取字段的值
                    Object value = field.get(netVcaDevAbility);
                    if (value instanceof Byte && ((Byte) value) != 0) {
                        if (!fieldName.equals("dwSize") ||!fieldName.equals("byVCAChanNum")  ) {
                            switch (fieldName) {
                                case "byFSnapChanNum":
                                    ability =ability+"人脸抓拍能力"+",";
                                    break;
                                case "byHumanRecognitionNum":
                                    ability =ability+"人体目标检测能力"+",";
                                    break;
                                case "byRoadDetectionNum":
                                    ability =ability+"道路检测能力"+",";
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    if (index == fields.length-1 &&ability.length()!=0) {
                        ability = ability.substring(0, ability.length() - 1);
                    }
                    index++;
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            log.error("ZMCAAA:"+ability);
//            LambdaQueryWrapper<Ape> queryWrapper = new LambdaQueryWrapper<Ape>();
//            queryWrapper.eq(Ape::getIPAddr, ip); // 设置查询条件

            LambdaUpdateWrapper<Ape> updateWrapper = Wrappers.<Ape>lambdaUpdate();
            // 设置更新条件为 id 与给定的 id 匹配，并且 email 不等于新的 email 值
            updateWrapper.eq(Ape::getIPAddr, ip).ne(Ape::getAbility,ability).set(Ape::getAbility,ability);
            int result = apeMapper.update(null, updateWrapper);
//            log.error("getCameraDeviceAbility NET_VCA_DEV_ABILITY======> size==============:{}\n", size);
//
//            log.error(" byVCAChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byVCAChanNum);
//            log.error(" byPlateChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byPlateChanNum);
//            log.error(" byBBaseChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byBBaseChanNum);
//            log.error(" byBAdvanceChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byBAdvanceChanNum);
//            log.error(" byBFullChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byBFullChanNum);
//            log.error(" byATMChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byATMChanNum);
//            log.error(" byPDCChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byPDCChanNum);
//            log.error(" byITSChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byITSChanNum);
//            log.error(" byBPrisonChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byBPrisonChanNum);
//            log.error(" byFSnapChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byFSnapChanNum);
//            log.error(" byFSnapRecogChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byFSnapRecogChanNum);
//            log.error(" byFRetrievalChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byFRetrievalChanNum);
//            log.error(" bySupport:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySupport);
//            log.error(" byFRecogChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byFRecogChanNum);
//            log.error(" byBPPerimeterChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byBPPerimeterChanNum);
//            log.error(" byTPSChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byTPSChanNum);
//            log.error(" byTFSChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byTFSChanNum);
//            log.error(" byFSnapBFullChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byFSnapBFullChanNum);
//            log.error(" byHeatMapChanNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byHeatMapChanNum);
//            log.error(" bySmartVehicleNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySmartVehicleNum);
//            log.error(" bySmartHVTNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySmartHVTNum);
//            log.error(" bySmartNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySmartNum);
//            log.error(" byVehicleNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byVehicleNum);
//            log.error(" bySmartRoadDetectionNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySmartRoadDetectionNum);
//            log.error(" bySmartFaceDetectionNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySmartFaceDetectionNum);
//            log.error(" bySmartHeatMapNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySmartHeatMapNum);
//            log.error(" byHumanRecognitionNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byHumanRecognitionNum);
//            log.error(" byEdcationStudentNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byEdcationStudentNum);
//            log.error(" byRoadDetectionNum:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byRoadDetectionNum);
//            log.error(" byPersonDensityDetection:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).byPersonDensityDetection);
//            log.error(" bySafetyHelmetDetection:{}",((HCNetSDK.NET_VCA_DEV_ABILITY)netVcaDevAbility).bySafetyHelmetDetection);
//
//            byte[] byAbility =  netVcaDevAbility.getPointer().getByteArray(4,size-4);
//            for (int i = 0; i < (size-4); i++) {
//
//                log.error("getCameraDeviceAbility i:{}, byte:{}\n", i ,byAbility[i]);
//            }
        }catch (Exception e)
        {
            log.error("getCameraDeviceAbility failed",e);
        }
        return 0;
    }

    public static int startApeAlarm(String device_ip, int port, String user, String passwd)
    {
        //用户注册
        HCNetSDK.NET_DVR_DEVICEINFO_V30  strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30();
        // int  userId = hCNetSDK.NET_DVR_Login_V30(device_ip, (short)port, user, passwd, strDeviceInfo);

        int userId = login_V40(device_ip, (short)port, user, passwd);
        log.info("login_V40 ==> ip:"+ device_ip + ",port:"+port +",user:"+user+",passwd"+passwd+",userId"+userId);
        if (userId == -1) {
            m_sDeviceIP = "";//登录未成功,IP置为空
            int error = hCNetSDK.NET_DVR_GetLastError();
            log.info("登陆注册失败,错误码：" + error);
            String res = "登录失败"+error;
            LambdaUpdateWrapper<Ape> updateWrapper = Wrappers.<Ape>lambdaUpdate();
            // 设置更新条件为 id 与给定的 id 匹配，并且 email 不等于新的 email 值
            updateWrapper.eq(Ape::getIPAddr, device_ip).set(Ape::getAbility,res);
            int result = apeMapper.update(null, updateWrapper);
            log.info("更新登录"+result);
            //如果已经注册,注销
            if (lUserID > -1) {
                hCNetSDK.NET_DVR_Logout(lUserID);
            }

            return -1;
        } else {
            LambdaUpdateWrapper<Ape> updateWrapper = Wrappers.<Ape>lambdaUpdate();
            // 设置更新条件为 id 与给定的 id 匹配，并且 email 不等于新的 email 值
            updateWrapper.eq(Ape::getIPAddr, device_ip).set(Ape::getAbility,"已登录");
            int result = apeMapper.update(null, updateWrapper);
            log.info("登陆注册成功");
        }

        getCameraDeviceAbility(userId,device_ip);


        //设置报警回调函数
        if (fMSFCallBack == null) {
            log.info("ZMC8888888888");
            fMSFCallBack = new FMSGCallBack_V31();
            String UserData = "UserData_50";
            HCNetSDK.BYTE_ARRAY UserDataByte = new HCNetSDK.BYTE_ARRAY(25);
            UserDataByte.read();
            UserDataByte.byValue = UserData.getBytes();
            UserDataByte.write();
            Pointer pUserDataByte = UserDataByte.getPointer();

            Pointer pUser = null;
            log.info("ZMC999999");
            if (!hCNetSDK.NET_DVR_SetDVRMessageCallBack_V50(0, fMSFCallBack, pUserDataByte)) {
                log.info("NET_DVR_SetDVRMessageCallBack_V50 设置回调函数失败!");
                return -2;
            } else {
                log.info("NET_DVR_SetDVRMessageCallBack_V50 设置回调函数成功!");
            }
        }

        /** 设备上传的报警信息是COMM_VCA_ALARM(0x4993)类型，
         在SDK初始化之后增加调用NET_DVR_SetSDKLocalCfg(enumType为NET_DVR_LOCAL_CFG_TYPE_GENERAL)设置通用参数NET_DVR_LOCAL_GENERAL_CFG的byAlarmJsonPictureSeparate为1，
         将Json数据和图片数据分离上传，这样设置之后，报警布防回调函数里面接收到的报警信息类型为COMM_ISAPI_ALARM(0x6009)，
         报警信息结构体为NET_DVR_ALARM_ISAPI_INFO（与设备无关，SDK封装的数据结构），更便于解析。*/
        HCNetSDK.NET_DVR_LOCAL_GENERAL_CFG struNET_DVR_LOCAL_GENERAL_CFG = new HCNetSDK.NET_DVR_LOCAL_GENERAL_CFG();
        struNET_DVR_LOCAL_GENERAL_CFG.byAlarmJsonPictureSeparate = 1;   //设置JSON透传报警数据和图片分离
        struNET_DVR_LOCAL_GENERAL_CFG.write();
        Pointer pStrNET_DVR_LOCAL_GENERAL_CFG = struNET_DVR_LOCAL_GENERAL_CFG.getPointer();
        hCNetSDK.NET_DVR_SetSDKLocalCfg(17, pStrNET_DVR_LOCAL_GENERAL_CFG);

//      setAlarm();//报警布防

        //报警布防失败，则注销
        if (!setAlarm_V50(userId))
        {
            stopApeAlarm(userId);
            return -1;
        }

        log.info("报警布防成功");
        return userId;
    }

    public static void stopApeAlarm(int userId)
    {
        //如果已经注册,注销
        if (userId > -1) {
            hCNetSDK.NET_DVR_Logout(userId);
            log.info("注销成功");
        }
    }

    public static boolean sdk_net_dvr_init()
    {
        if (hCNetSDK == null) {

            if (SdkInited)
                sdk_net_dvr_cleanup();

            if (!createSDKInstance()) {
                log.info("Load HCNetSDK fail");
                return false;
            }
            SdkInited = true;
        } else {
            return true;
        }

        //linux系统建议调用以下接口加载组件库
        if (osSelect.isLinux()) {
            HCNetSDK.BYTE_ARRAY ptrByteArray1 = new HCNetSDK.BYTE_ARRAY(256);
            HCNetSDK.BYTE_ARRAY ptrByteArray2 = new HCNetSDK.BYTE_ARRAY(256);
            //这里是库的绝对路径，请根据实际情况修改，注意改路径必须有访问权限System.getProperty("user.dir")
            String strPath1 = "/usr/lib64/libcrypto.so.1.1";
            String strPath2 = "/usr/lib64/libssl.so.1.1";

            System.arraycopy(strPath1.getBytes(), 0, ptrByteArray1.byValue, 0, strPath1.length());
            ptrByteArray1.write();
            hCNetSDK.NET_DVR_SetSDKInitCfg(3, ptrByteArray1.getPointer());

            System.arraycopy(strPath2.getBytes(), 0, ptrByteArray2.byValue, 0, strPath2.length());
            ptrByteArray2.write();
            hCNetSDK.NET_DVR_SetSDKInitCfg(4, ptrByteArray2.getPointer());

            String strPathCom ="/usr/lib64";

            log.info("strPathCom="+strPathCom);
            HCNetSDK.NET_DVR_LOCAL_SDK_PATH struComPath = new HCNetSDK.NET_DVR_LOCAL_SDK_PATH();
            System.arraycopy(strPathCom.getBytes(), 0, struComPath.sPath, 0, strPathCom.length());
            struComPath.write();
            hCNetSDK.NET_DVR_SetSDKInitCfg(2, struComPath.getPointer());
        }

        /*初始化*/
        boolean initSuc = hCNetSDK.NET_DVR_Init();
        if (initSuc != true) {
            log.info("HCNetSDK 初始化失败");
            return false;
        }

        /**加载日志*/
        hCNetSDK.NET_DVR_SetLogToFile(3, "./sdklog", false);
        return true;
    }

    public static void sdk_net_dvr_cleanup()
    {
        //cleanup SDK
        hCNetSDK.NET_DVR_Cleanup();
        hCNetSDK = null;
//        SdkInited = false;
        log.info("SDK 销毁清除");
    }

}
